import { computed } from 'vue'
import { useGlobalStoreWithOut } from '@/store/modules/global'
import { urlParams } from '@/utils/util'
import { downloadByData } from '@/utils/file/download'

export const useExport = async (
  api: string,
  fileName: string,
  params: any,
  method = 'GET'
) => {
  // TODO 后端还没定
  const BASE_URL = ''

  let exportUrl = BASE_URL + api
  // 拼接参数
  if (method === 'GET') {
    exportUrl = urlParams(exportUrl, params)
  }
  // 获取token
  const globalStore = useGlobalStoreWithOut()

  // @ts-ignore
  const token = computed(() => globalStore.token)

  const res = await fetch(exportUrl, {
    method,
    headers: {
      Authorization: token.value,
      token: globalStore.token,
      'Content-Type': 'application/json',
      // ['X-CLIENT-ID']: process.env.VUE_APP_CLIENT_ID
    },
    body:
      method.toLocaleLowerCase() == 'post' && params
        ? JSON.stringify(params)
        : undefined
  })

  const blobUrl = await res.blob()
  downloadByData(blobUrl, fileName)
}